#!/usr/bin/env python
#_*_ coding:utf-8 _*_
'''
Created on 2016年5月31日
@author: liuhaozzu
'''
from django.utils.safestring import mark_safe

class PageInfo(object):
    def __init__(self,current_page, all_count, per_item=5):
        self.CurrentPage=current_page
        self.AllCount=all_count
        self.Per_item=per_item
    @property
    def start(self):
        start=(self.CurrentPage-1)*self.Per_item
        return start
    
    '''
    per_item=5
    #计算页数
    tmp=divmod(count, per_item)
    if tmp[1]==0:
        all_page_count=tmp[0]
    else:
        all_page_count=tmp[0]+1
    
    #优化第一页和最后一页时，上下页报错的问题
    if page<=0:
        page=1
    elif page > all_page_count:
        page=all_page_count
    start=(page-1)*5
    end=page*5
    if end > all_page_count*5:
        end=all_page_count-1
    print start,end
    '''
    @property
    def end(self):
        end=self.CurrentPage*self.Per_item
        if end>self.AllCount:
            end=self.AllCount-1
        return end
    @property
    def all_page_count(self):
        
        tmp=divmod(self.AllCount, self.Per_item)
        if tmp[1]==0:
            all_page_count=tmp[0]
        else:
            all_page_count=tmp[0]+1
        return all_page_count

def pager(page, all_page_count):
    '''
    page: 当前页
    all_page_count:总页数
    return 生成的分页标签
    '''
    
    page_html=[]
    
    #每页显示11个页码
    if all_page_count<11:
        begin=0
        end=all_page_count
    else:
        if page<6:
            begin=0
            end=12
        else:
            if page+6>all_page_count:
                begin=page-6
                end=all_page_count
            else:
                begin=page-6
                end=page+5
    first_html="<a href='/app05/index/%d'>首页</a>" %(1,)
    pre_html="<a href='/app05/index/%d'>上一页</a>" %(page-1,)
    
    page_html.append(first_html)
    page_html.append(pre_html)
    for i in range(begin,end):
        if i==0 and page !=1:
            a_html="<a href='/app05/index/%d'>%d</a>" %(i+1,i+1,)
        elif i==0 and page==1:
            a_html="<a class='selected' href='/app05/index/%d'>%d</a>" %(i+1,i+1,)
        elif (i==(page-1)==all_page_count-1):
            a_html="<a class='selected' href='/app05/index/%d'>%d</a>" %(all_page_count,all_page_count,)
        elif page!=all_page_count and i==all_page_count-1:
            a_html="<a href='/app05/index/%d'>%d</a>" %(all_page_count,all_page_count,)
        else:
            if page==i+1:
                a_html="<a class='selected' href='/app05/index/%d'>%d</a>" %(i+1,i+1)
            else:
                a_html="<a href='/app05/index/%d'>%d</a>" %(i+1,i+1)
            
        page_html.append(a_html)
    next_html="<a href='/app05/index/%d'>下一页</a>" %(page+1,)
    page_html.append(next_html)
    last_html="<a href='/app05/index/%d'>尾页</a>" %(all_page_count,)
    page_html.append(last_html)
    page_str=mark_safe(''.join(page_html))
    return page_str